﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnterpriseFund.Common;
using System.Configuration;
using System.Data;

namespace EnterpriseFund.Controllers
{
        [OutputCache(Duration = 0, VaryByParam = "none")]   
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns>视图</returns>
        [HttpPost]
        public ActionResult Login()
        {
            string loginid = Fetch.Post("txtUserName").Trim();
            string password = Fetch.Post("txtPassword").Trim();
            string entityNo = ConfigurationManager.AppSettings["EntityNo"].ToString();
            string errorMessage = "";
            bool isSuccess = true;
            int result = this.sysLogin(loginid, password, entityNo);
            if (result == 1)
            {
                errorMessage = "用户名或密码错误请重新填写！";
                isSuccess = false;
            }
            else if (result == 2)
            {
                errorMessage = "你的帐号已经被禁止登陆！";
                isSuccess = false;
            }
            else if (result == 3)
            {

                errorMessage = "你的用户名已过期，不能登陆！";
                isSuccess = false;
            }
            else if (result == 4)
            {
                errorMessage = "ip受限制,请联系管理员!";
            }
            else if (result == 5)
            {
                errorMessage = "验证码错误，请重新填写";
            }
            else if (result == 200)
            {
                errorMessage = "";
            }

            ViewData["UserName"] = loginid;
            if (errorMessage != "")
            {
                ViewData["jsAlert"] = errorMessage;
                return View("index");
            }
            else
            {
                BLL.PrvUser prvUserBLL = new BLL.PrvUser();
                string currenttheme = prvUserBLL.GetThemePrvUser(entityNo, loginid);
                if (string.IsNullOrEmpty(currenttheme))
                {
                    bool bl = prvUserBLL.UpdateThemePrvUser(entityNo, loginid, OperateSession.usertheme);
                    OperateSession.SetToCacheRequest(OperateSession.usertheme, "CurrentUserTheme");
                }
                else
                {
                    OperateSession.SetToCacheRequest(currenttheme, "CurrentUserTheme");
                }
                ActionResult actionResult = null;
                actionResult = Redirect(Url.Action("Index", "Index"));
                return actionResult;
                
            }
        }

        private int sysLogin(string loginid, string password, string entityNo)
        {
            #region ip控制验证
            /*修改者：王磊
              修改日期：2010-08-12
            */
            if (!Fetch.IpCheck())
            {
                return 4;//表示ip受限制
            }
            #endregion

            //if (Fetch.Post("Verify").Trim().ToLower() != Request.Cookies["ValidateCode"].Value.Trim().ToLower())
            //{
              
            //    return 5;
            //}


            BLL.PrvUser prvUserBLL = new BLL.PrvUser();
            Model.PrvUser prvUserObject = prvUserBLL.GetModelByNameAndPassword(loginid, password, entityNo);

            if (prvUserObject == null) //用户名或密码错误
            {
                return 1;
            }
            else
            {
                if (prvUserObject.FProhibitLogin == 1)
                {
                    return 2;
                }
                else if (prvUserObject.FForeverAvailable != 1)//如果账号不是永久有效，就判断该账号是否已过期
                {
                    DateTime timenow = DateTime.Now.AddDays(-1);
                    if (timenow > prvUserObject.FAvailableDate)//已过期
                    {
                        return 3;
                    }
                }

                OperateSession.add("LogID", prvUserObject.FLogID);//把登陆ID保存到Session
                BLL.HREmpl hREmplBLL = new BLL.HREmpl();
                DataSet ds = hREmplBLL.GetEmplFromViewByEmplNo(prvUserObject.FEmplNo, entityNo);
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i]["FIsMainPosition"].ToString() == "Y")
                    {
                        OperateSession.add(GlobalConstant.PARAM_USERNAME, dt.Rows[i]["FEmpName"].ToString());
                        OperateSession.add(GlobalConstant.PARAM_DEPTNO, dt.Rows[i]["FDeptNo"].ToString());
                        break;
                    }

                }

              //登陆用户名称
                OperateSession.add("FLastLoginTime", string.Format("{0:yyyy-MM-dd}", prvUserObject.FLastLoginTime));//上次登陆时间
                OperateSession.add("LastLoginIPAddr", prvUserObject.FLastLoginIPAddr);//上次登陆IP
                OperateSession.add("EntityNo", prvUserObject.FEntityNo);//公司编码
                OperateSession.add(GlobalConstant.PARAM_FEMPLNO, prvUserObject.FEmplNo);//员工编号

                //从数据库获取Ntko Office控件序列号
                BLL.Entity _entityBll = new BLL.Entity();
                Model.Entity _entityModel = _entityBll.GetModel(prvUserObject.FEntityNo);
                if (_entityModel != null)
                {
                    OperateSession.add("ProductCaption", _entityModel.FNtkoCaption);
                    OperateSession.add("ProductKey", _entityModel.FNtkoKey);
                }

                prvUserObject.FLastLoginTime = DateTime.Now;
                prvUserObject.FLastLoginIPAddr = Request.UserHostAddress;
                prvUserObject.FLoginCnt += 1;
                prvUserBLL.Update(prvUserObject);//更新最近登陆时间等信息

                //更新组织结构表最近登录相关信息

                Model.Entity entityObject = new Model.Entity();
                entityObject.FEntityNo = entityNo;
                entityObject.FLastLoginIPAddr = Request.UserHostAddress;
                entityObject.FLogID = loginid;
                entityObject.FAccessDate = DateTime.Now;

                BLL.Entity entityBll = new BLL.Entity();
                entityBll.UpdateByEntityNo(entityObject);
                return 200;
            }
        }

    }
}
